﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using HgRemoteContracts;
using HgRemoteServer.Config;
using System.Configuration;
using log4net;

namespace HgRemoteServer
{
	public class Service
	{
		private ServiceHost svcHost;
		private ILog log = LogManager.GetLogger(typeof(Service));

		public void Start()
		{
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
			
			log.Debug("Starting service.");
			svcHost = new ServiceHost(typeof(HgServer));
			svcHost.Description.Behaviors.Add(new LoggerBehavior());
			svcHost.Open();
			log.Debug("Service started.");
		}

		public void Stop()
		{
			log.Debug("Service stopping.");
			if (svcHost != null)
			{
				if (svcHost.State != CommunicationState.Closed)
					svcHost.Close();
				svcHost = null;
			}
			log.Debug("Service stopped.");
		}

		void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			if (e.IsTerminating)
				log.Fatal("Unhandled AppDomain Exception", e.ExceptionObject as Exception);
			else
				log.Error("Non-fatal AppDomain Exception", e.ExceptionObject as Exception);
		}

	}
}
